const axios = require("axios");
var crypto = require("crypto");
var random = require("string-random");
const { to } = require("./utils");
// 参考https://zhuanlan.zhihu.com/p/81945858

const APPID = `20211012000970677`;
const key = `RCOAR3Cabbk5r2ycnZ61`;
//翻译
function translate(str) {
  const { salt, sign } = getSign(str);
  return to(
    axios(
      url_encode(
        `http://api.fanyi.baidu.com/api/trans/vip/translate?appid=${APPID}&salt=${salt}&sign=${sign}&from=zh&to=en&q=${str}`
      )
    ).then((res) => {
      console.log("translate res", res.data);
      return res.data.trans_result[0].dst;
    })
  );
}

// 获取签名
function getSign(str) {
  const salt = random(10, { letters: false });
  // console.log({ salt });
  const sign = crypto
    .createHash("md5")
    .update(`${APPID}${str}${salt}${key}`)
    .digest("hex");
  // console.log({ sign });
  return { salt, sign };
}

// get请求带中文
function url_encode(url) {
  url = encodeURIComponent(url);
  url = url.replace(/%3A/g, ":");
  url = url.replace(/%2F/g, "/");
  url = url.replace(/%3F/g, "?");
  url = url.replace(/%3D/g, "=");
  url = url.replace(/%26/g, "&");

  return url;
}
// ————————————————
// 版权声明：本文为CSDN博主「进击的小民工」的原创文章，遵循CC 4.0 BY-SA版权协议，转载请附上原文出处链接及本声明。
// 原文链接：https://blog.csdn.net/zsq199771/article/details/118183071

module.exports = {
  translate,
};
